<?php

class InvoiceLedgerController extends Controller {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/customer';

    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            array(
                'application.filters.RequireLoginFilter',
            ),
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions

                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

  
    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate($invoice) {
        /*
        $jsonData = json_decode($_REQUEST['data'], true);
        foreach ($jsonData as $item) {
            $model = new InvoiceLedger;
            $model->attributes = $item;
            $model->description = $item['description'];
            $model->invoice = $_GET['invoice'];
            $inventotyModel = Inventory::model()->find('partno=:partno', array(
            'partno' => $model->partno));
            $subcat = Invsubcategories::model()->find('subcategory=:subcat', array(
                'subcat' => $inventotyModel->subcat));
            if ($subcat->applymarkup == 'Average Cost')
               $model->cost =  $inventotyModel->averagecost;
            else
               $model->cost =   $inventotyModel->baseprice;
            $model->scredit = $inventotyModel->salescredit;
            $model->sdebit = $inventotyModel->salesdebit;
            $model->cdebit = $inventotyModel->costcredit;
            $model->ccredit = $inventotyModel->costdebit;
            $model->status=1;
            if ($model->save())
                echo 'itemAdded';
        }
*/
        $model=new InvoiceLedger;
        $model->invoice=$invoice;
        $model->noprint=0;
        $model->taxed=0;
        $model->status=2;
        if($model->save()){
            echo "save successfull";
        }
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id=NULL) {
        if($id!=0){
            $model = $this->loadModel($id);
        
            $model->attributes = $_REQUEST;
            if($model->status==2){
                $model->status=1;
            }
            if (isset($_REQUEST['description']))
                $model->description = $_REQUEST['description'];        

            if ($model->save())
                echo 'Update succes';
        }elseif($id==0){
            $model=new InvoiceLedger;
            $model->attributes=$_REQUEST;
            $model->id=NULL;
            $model->status=2;
            if($model->save()){
                echo 'Add successful';                
            }else{
                echo json_encode($model->getErrors());
            }
        }
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {

        $model = $this->loadModel($id);
        $invoice = $model->invoice;
        $model->delete();
        $this->redirect(array('invoices/update', 'invoice' => $invoice));
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $dataProvider = new CActiveDataProvider('InvoiceLedger');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

   

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $model = InvoiceLedger::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    //TODO move this code to model
    public function actionGetInvoiceItems($invoice, $page=1, $sort=NULL, $dir=NULL) {
        //we decrease $page by 1 because in Extjs first page is 1, but in our sql first page is 0;
        if ($page > 0)
            $page--;

        $items = new CActiveDataProvider('InvoiceLedger', array(
                    'criteria' => array(
                        'condition' => "invoice='$invoice'",
                        'order' => $sort != NULL ? $sort . ' ' . $dir : '',
                    ),
                    'pagination' => array(
                        'pageSize' => 20,
                        'currentPage' => $page,
                    ),
                ));

        $itemsList = array();
        if ($items->getTotalItemCount() > 0) {
            $itemsList['totalCount'] = $items->getTotalItemCount();
            $itemsList['type'] = 'Items';
            foreach ($items->getData() as $i=>$item) {
                $itemsList['data'][$i] = $item->getAttributes();
                $itemsList['data'][$i]['noprinttext']=$item->getYesNoValue($item->noprint);
                $itemsList['data'][$i]['taxedtext']=$item->getYesNoValue($item->taxed);
            }
            echo json_encode($itemsList);
        }
        Yii::app()->end();
    }

    public function actionGetItemsCost() {
        $totalCost = 0;
        $jsonData = json_decode($_REQUEST['data'], true);
      
        foreach ($jsonData as $item) {
         $model = Inventory::model()->find('partno=:partno', array(
            'partno' => $item['partno']));

        // echo $model->description;
        $subcat = Invsubcategories::model()->find('subcategory=:subcat', array(
            'subcat' => $model->subcat));
          if (isset($subcat)&&$subcat->applymarkup == 'Average Cost')
           $totalCost+=    $model->averagecost*$item['qty'];
        else
       
            $totalCost+=  $model->baseprice*$item['qty'];
        }
        echo number_format($totalCost, 2, '.', '');
      
       
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'invoice-ledger-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

}
